package com.example.r.zhproject;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView= (RecyclerView) findViewById(R.id.id_recycler_view);
        final List<String> mData=new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            mData.add(i+"");
        }
        mRecyclerView.setLayoutManager(mLinearLayoutManager=new LinearLayoutManager(this));
        mRecyclerView.setAdapter(new CommonAdapter(MainActivity.this,
                R.layout.item,mData) {
            @Override
            protected void convert(ViewHolder holder, Object o, int position) {

                    holder.setText(R.id.id_tv_title,"标题balabalabalabalblablalblablalblablalblab");

                if (position > 0 && position % 6 == 0) {
                    holder.setVisible(R.id.id_tv_title, false);
                    holder.setVisible(R.id.id_tv_desc, false);
                    holder.setVisible(R.id.id_iv_ad, true);
                } else {
                    holder.setVisible(R.id.id_tv_title, true);
                    holder.setVisible(R.id.id_tv_desc, true);
                    holder.setVisible(R.id.id_iv_ad, false);
                }
            }
        });
        /**
         *
         * 通过addOnScrollListener监听，当滚动时，拿到所有可见的Item，找出正在显示图片的Item。
         * 然后调用setDy，dy的值为`mLinearLayoutManager.getHeight() - view.getTop()`，
         * 当View从最底部出现的时候为0，当View到达最顶部的时候为当前rv的高度。
         * 你可以合理的利用setDy传入的值，做移动差，显示区域从上到下等，都可以。
         *
         *
         */
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int fPos = mLinearLayoutManager.findFirstVisibleItemPosition();
                int lPos = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                for (int i = fPos; i <= lPos; i++) {
                    View view = mLinearLayoutManager.findViewByPosition(i);
                    AdImageView adImageView = view.findViewById(R.id.id_iv_ad);
                    if (adImageView.getVisibility() == View.VISIBLE) {
                        adImageView.setDx(mLinearLayoutManager.getHeight() - view.getTop());
                    }
                }
            }
        });
    }
}
